import subprocess
import asyncio
import locale
system_encoding = locale.getpreferredencoding()  # Windows 默认 'cp936'（gbk）


async def read_stream(stream, stream_name):
    while True:
        line = await stream.readline()
        if not line:
            break
        decoded_line = line.decode(system_encoding, errors='replace')
        print(f"{stream_name}: {decoded_line.strip()}")


async def run_command():
    proc = subprocess.Popen(["ping", "baidu.com"], 
                       stdout=subprocess.PIPE, 
                       stderr=subprocess.PIPE)

    # 创建两个任务并行读取 stdout 和 stderr
    await asyncio.gather(
        read_stream(proc.stdout, "STDOUT"),
        read_stream(proc.stderr, "STDERR"),
    )

    # 等待进程结束
    proc.wait()
    print("Process exited with code:", proc.returncode)

asyncio.run(run_command())
